﻿using Opc.Ua;
using Opc.Ua.Configuration;
using SD.Infrastructure;
using SD.IOC.Core.Mediators;
using SD.OpcProxy.OpcService.Extensions;
using System;

namespace SD.OpcProxy.OpcService.Host
{
    /// <summary>
    /// 服务启动器
    /// </summary>
    public class ServiceLauncher
    {
        /// <summary>
        /// OPC应用实例
        /// </summary>
        private readonly ApplicationInstance _opcApplication;

        /// <summary>
        /// 构造器
        /// </summary>
        public ServiceLauncher()
        {
            this._opcApplication = new ApplicationInstance
            {
                ApplicationType = ApplicationType.Server,
                ConfigSectionName = FrameworkSection.Setting.ServiceDisplayName.Value
            };
        }

        /// <summary>
        /// 开始
        /// </summary>
        public void Start()
        {
            //初始化依赖注入
            OpcProxyExtension.InitializeDependencies();
            Console.WriteLine("依赖注入容器已初始化...");

            //初始化OPC代理服务
            OpcProxyExtension.InitializeProxyService(this._opcApplication);
            Console.WriteLine("OPC代理服务已启动...");

            //初始化OPC代理适配器
            OpcProxyExtension.InitializeProxyAdapters();
            Console.WriteLine("OPC代理适配器已初始化...");
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            //关闭OPC代理服务
            this._opcApplication?.Stop();
            Console.WriteLine("OPC代理服务已关闭...");

            //清理调度任务、会话
            OpcProxyExtension.FinalizeProxySchedule();
            Console.WriteLine("调度任务、会话已清理...");

            //清理依赖注入
            ResolveMediator.Dispose();
            Console.WriteLine("依赖注入容器已清理...");
        }
    }
}
